package com.xt.website_manager.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xt.website_manager.dao.UserDao;
import com.xt.website_manager.po.News;
import com.xt.website_manager.po.User;
import com.xt.website_manager.service.UserService;
import com.xt.website_manager.util.MD5Util;
import com.xt.website_manager.util.MyPageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: jiangyu
 * @Date: 2019/9/2 11:33
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;


    /**
     * 登录校验
     */
    @Override
    public User findUserByUnameAndPwd(User user) {
        //将接受的密码加密
        String md5Password = MD5Util.inputPassToFormPass(user.getPassword());
        user.setPassword(md5Password);
        user = userDao.findUserByUnameAndPwd(user);
        return user;
    }

    /**
     * 查询全部用户
     */
    @Override
    public MyPageInfo<User> findAllUsers(MyPageInfo<User> pageInfo) {
        PageHelper.startPage(pageInfo.getPageNum(), 9);
        List<User> list = userDao.findAllUsers(pageInfo);
        MyPageInfo<User> page = new MyPageInfo<User>(list, 5);
        //封装之前的信息
        page.setSearchProName(pageInfo.getSearchProName());
        page.setCid(pageInfo.getCid());
        page.setSearchCsid(pageInfo.getSearchCsid());
        page.setSearchUsername(pageInfo.getSearchUsername());
        return page;
    }


    /**
     * 添加用户
     */
    @Override
    public void addUser(User user) {
        try {
            //将密码进行MD5加密
            String md5Password = MD5Util.inputPassToFormPass(user.getPassword());
            user.setPassword(md5Password);
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 设置时间
            user.setCreatetime(df.parse(df.format(new Date())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        userDao.addUser(user);
    }

    /**
     * 查询用户名是否存在
     */
    @Override
    public User checkUsername(String username) {
        return userDao.checkUsername(username);
    }

    /**
     * 删除用户
     */
    @Override
    public void delUset(Integer id) {
        userDao.delUset(id);
    }

    /**
     *  查询用户详情
     */
    @Override
    public User userDetails(Integer id) {
        return userDao.userDetails(id);
    }

    /**
     *  修改用户信息
     */
    @Override
    public void updateUser(User user) {
        System.out.println("加密前："+user.getPassword());
        String md5Password = MD5Util.inputPassToFormPass(user.getPassword());
        user.setPassword(md5Password);
        System.out.println("加密后："+user.getPassword());
        userDao.updateUser(user);
    }
}
